<script lang="ts" setup>
import { useVbenModal } from '@vben/common-ui';

import { Button, Input, InputGroup } from 'ant-design-vue';

import { useThemeStore } from '#/store';

import FileBlockWidgetArrayInputModal from './FileBlockWidgetArrayInputModal.vue';

// 接收父组件传递的属性和事件
defineOptions({
  name: 'FileBlockWidgetInput',
});
const props = withDefaults(
  defineProps<{
    item: Record<string, any>;
    name?: string;
    placeholder?: string;
    title: string;
    value: any[];
  }>(),
  {
    item: () => ({}),
    placeholder: '',
    value: () => [],
    title: '',
    name: '',
  },
);

// emit 用于通知父组件更新值
const emit = defineEmits<{
  (e: 'update:value', value: any): void;
}>();
const { setThemeInfo } = useThemeStore();
const value = ref(`${props.value.length}条数据`);
const [Modal, modalApi] = useVbenModal({
  // 连接抽离的组件
  connectedComponent: FileBlockWidgetArrayInputModal,
  onClosed() {
    const modalData = modalApi.getData();
    value.value = `${modalData.count}条数据`;
    emit('update:value', modalData.dataSource); // 发射更新事件给父组件
  },
});

function openModal() {
  modalApi.setData({
    item: props.item,
    value: props.value,
  });
  modalApi.setState({
    title: `${props.title}-数据列表`,
  });
  setThemeInfo({ var: props.name });
  modalApi.open();
}
watch(
  () => props.value,
  (newValue) => {
    value.value = `${newValue.length}条数据`;
  },
);
</script>

<template>
  <div>
    <Modal />
    <InputGroup compact>
      <Input
        v-model:value="value"
        disabled
        style="width: calc(400px - 200px)"
      />
      <Button type="primary" @click="openModal">添加数据</Button>
    </InputGroup>
  </div>
</template>
